package crontab

import (
	"gitee.com/vzr/gearutil/log"
	"time"
)

// DayTask 每日凌晨近零点任务
func DayTask(task func()) {
	for {
		now := time.Now()
		// 2019-01-08 10:22:22 修改统计时间为当天的23:58分
		nextTick := time.Date(now.Year(), now.Month(), now.Day(), 23, 58, 0, 0, now.Location())
		// 当天23:58执行之后计算下一次时间时会是当前时间的之前时间，这时就需要加24小时来创建下一天的定时任务
		if nextTick.Before(now) {
			nextTick = nextTick.Add(time.Hour * 24)
		}
		log.Info.Println("执行近零点任务......")
		t := time.NewTicker(nextTick.Sub(now))
		<-t.C
		task()
	}
}

// DayZeroTask 每日凌晨整点任务
func DayZeroTask(task func()) {
	for {
		now := time.Now()
		next := now.Add(time.Hour * 24)
		next = time.Date(next.Year(), next.Month(), next.Day(), 0, 0, 0, 0, next.Location())
		t := time.NewTimer(next.Sub(now))
		<-t.C
		log.Info.Println("执行每日零点任务......")
		task()
	}
}

// HourTask 每小时整点任务
func HourTask(hourDuration time.Duration, task func()) {
	for {
		now := time.Now()
		next := now.Add(time.Hour * hourDuration)
		next = time.Date(next.Year(), next.Month(), next.Day(), next.Hour(), 0, 0, 0, next.Location())
		//log.Debug.Println(next)
		t := time.NewTimer(next.Sub(now))
		<-t.C
		log.Info.Println("执行每小时整点任务......")
		task()
	}
}

// TickerTask 定时周期任务
// second 任务执行间隔秒数
// task 所要执行的任务
func TickerTask(second int64, task func()) {
	ticker := time.NewTicker(time.Duration(int64(time.Second) * second))
	go func() {
		for range ticker.C {
			task()
		}
	}()
}

// TickerTaskWeekDay 执行定时任务任务(排除夜间、周六日)
func TickerTaskWeekDay(second int64, task func()) {
	ticker := time.NewTicker(time.Duration(int64(time.Second) * second))
	go func() {
		for key := range ticker.C {
			// 只在工作日的非夜间时段执行该任务
			if key.Weekday() != 0 && key.Weekday() != 6 && key.Hour() > 8 && key.Hour() < 20 {
				task()
			}
		}
	}()
}
